package com.idea.dsl.service;

import com.idea.dsl.model.DslRequest;
import com.idea.dsl.model.DslResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 业务规则解析服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessRuleParserService {
    
    private final DslGeneratorService dslGeneratorService;
    
    // 规则名称提取模式
    private static final Pattern RULE_NAME_PATTERN = Pattern.compile("([^_]+)_([^_]+)");
    
    // 字段名称提取模式
    private static final Pattern FIELD_PATTERN = Pattern.compile("([\\u4e00-\\u9fa5]+)");
    
    /**
     * 解析业务规则并生成DSL
     */
    public DslResponse parseBusinessRule(String ruleName, String relatedField, String ruleDescription) {
        log.info("开始解析业务规则: {}", ruleName);
        
        try {
            // 构建上下文信息
            Map<String, Object> context = buildRuleContext(ruleName, relatedField, ruleDescription);
            
            // 构建DSL生成请求
            DslRequest request = DslRequest.builder()
                    .description(ruleDescription)
                    .dslType("business-rule")
                    .template("business-rule")
                    .context(context)
                    .params(DslRequest.GenerationParams.builder()
                            .maxTokens(1500)
                            .temperature(0.3) // 较低温度确保结果稳定
                            .validate(true)
                            .build())
                    .build();
            
            // 生成DSL
            DslResponse response = dslGeneratorService.generateDsl(request);
            
            // 后处理：优化生成的DSL
            if (response.getStatus() == DslResponse.GenerationStatus.SUCCESS) {
                String optimizedDsl = optimizeGeneratedDsl(response.getDslContent(), context);
                response.setDslContent(optimizedDsl);
            }
            
            return response;
            
        } catch (Exception e) {
            log.error("业务规则解析失败: " + ruleName, e);
            return DslResponse.builder()
                    .status(DslResponse.GenerationStatus.FAILED)
                    .errorMessage("业务规则解析失败: " + e.getMessage())
                    .build();
        }
    }
    
    /**
     * 批量解析业务规则
     */
    public Map<String, DslResponse> parseBatchBusinessRules(Map<String, Map<String, String>> rulesData) {
        Map<String, DslResponse> results = new HashMap<>();
        
        for (Map.Entry<String, Map<String, String>> entry : rulesData.entrySet()) {
            String ruleId = entry.getKey();
            Map<String, String> ruleData = entry.getValue();
            
            String ruleName = ruleData.get("ruleName");
            String relatedField = ruleData.get("relatedField");
            String ruleDescription = ruleData.get("ruleDescription");
            
            DslResponse response = parseBusinessRule(ruleName, relatedField, ruleDescription);
            results.put(ruleId, response);
        }
        
        return results;
    }
    
    /**
     * 构建规则上下文
     */
    private Map<String, Object> buildRuleContext(String ruleName, String relatedField, String ruleDescription) {
        Map<String, Object> context = new HashMap<>();
        
        // 基本信息
        context.put("ruleName", ruleName);
        context.put("relatedField", relatedField);
        context.put("ruleDescription", ruleDescription);
        
        // 解析规则类型
        String ruleType = extractRuleType(ruleName, ruleDescription);
        context.put("ruleType", ruleType);
        
        // 解析字段名称
        String fieldName = extractFieldName(relatedField, ruleDescription);
        context.put("fieldName", fieldName);
        
        // 解析操作符
        String operator = extractOperator(ruleDescription);
        context.put("operator", operator);
        
        // 解析错误信息
        String errorMessage = extractErrorMessage(ruleDescription);
        context.put("errorMessage", errorMessage);
        
        // 生成规则ID
        String ruleId = generateRuleId(ruleName);
        context.put("ruleId", ruleId);
        
        return context;
    }
    
    /**
     * 提取规则类型
     */
    private String extractRuleType(String ruleName, String ruleDescription) {
        if (ruleName.contains("必填") || ruleDescription.contains("必填") || ruleDescription.contains("不能为空")) {
            return "required";
        } else if (ruleName.contains("格式") || ruleDescription.contains("格式")) {
            return "format";
        } else if (ruleName.contains("范围") || ruleDescription.contains("范围")) {
            return "range";
        } else if (ruleName.contains("唯一") || ruleDescription.contains("唯一")) {
            return "unique";
        } else {
            return "custom";
        }
    }
    
    /**
     * 提取字段名称
     */
    private String extractFieldName(String relatedField, String ruleDescription) {
        if (relatedField != null && !relatedField.trim().isEmpty()) {
            return relatedField.trim();
        }
        
        // 从描述中提取字段名称
        Matcher matcher = FIELD_PATTERN.matcher(ruleDescription);
        if (matcher.find()) {
            return matcher.group(1);
        }
        
        return "未知字段";
    }
    
    /**
     * 提取操作符
     */
    private String extractOperator(String ruleDescription) {
        if (ruleDescription.contains("不能为空") || ruleDescription.contains("必填")) {
            return "not_empty";
        } else if (ruleDescription.contains("等于")) {
            return "equals";
        } else if (ruleDescription.contains("包含")) {
            return "contains";
        } else if (ruleDescription.contains("大于")) {
            return "greater_than";
        } else if (ruleDescription.contains("小于")) {
            return "less_than";
        } else if (ruleDescription.contains("格式")) {
            return "regex";
        } else {
            return "custom";
        }
    }
    
    /**
     * 提取错误信息
     */
    private String extractErrorMessage(String ruleDescription) {
        // 查找引号中的错误信息
        Pattern messagePattern = Pattern.compile("[\"'](.*?)[\"']");
        Matcher matcher = messagePattern.matcher(ruleDescription);
        
        if (matcher.find()) {
            return matcher.group(1);
        }
        
        // 如果没有找到引号中的信息，生成默认错误信息
        return ruleDescription.length() > 50 ? 
            ruleDescription.substring(0, 50) + "..." : 
            ruleDescription;
    }
    
    /**
     * 生成规则ID
     */
    private String generateRuleId(String ruleName) {
        return "rule-" + ruleName.toLowerCase()
                .replaceAll("[\\u4e00-\\u9fa5]", "") // 移除中文字符
                .replaceAll("[^a-zA-Z0-9]", "-") // 替换特殊字符为连字符
                .replaceAll("-+", "-") // 合并多个连字符
                .replaceAll("^-|-$", ""); // 移除首尾连字符
    }
    
    /**
     * 优化生成的DSL
     */
    private String optimizeGeneratedDsl(String dslContent, Map<String, Object> context) {
        // 这里可以添加DSL优化逻辑
        // 例如：标准化字段名称、优化错误信息等
        
        String optimized = dslContent;
        
        // 替换上下文中的占位符
        if (context.containsKey("ruleId")) {
            optimized = optimized.replace("rule-xxx", context.get("ruleId").toString());
        }
        
        return optimized;
    }
}
